//清单类
utils = {
    setParam : function (name,value){
        localStorage.setItem(name,value)
    },
    getParam : function(name){
        return localStorage.getItem(name)
    }
}

product={
    id:0,
    name:"",
    num:0,
    price:0.00,
};
orderdetail={
    username:"",
    phone:"",
    address:"",
    zipcode:"",
    totalNumber:0,
    totalAmount:0.00    
}
 var xround = function(x, num){
           return Math.round(x * Math.pow(10, num)) / Math.pow(10, num) ;
        }
cart = {
    //向购物车中添加商品
    addproduct:function(product){
        var ShoppingCart = $api.getStorage("ShoppingCart");
        if(ShoppingCart==null||ShoppingCart==""){
            //第一次加入商品
            
            var _ratio = product.num/product.totalNum*100;
            
            var ratio = xround(_ratio,4)

            var jsonstr = {"productlist":[{"id":product.id,"name":product.name,"num":product.num,"price":product.price,"ratio":ratio,"img":product.img,"totalNum":product.totalNum,"surplus":product.surplus}],"totalNumber":product.num,"totalAmount":(product.price*product.num)};
            
            $api.setStorage("ShoppingCart","'"+JSON.stringify(jsonstr));
        }else{
            var jsonstr = JSON.parse(ShoppingCart.substr(1,ShoppingCart.length));
            var productlist = jsonstr.productlist;
            var result=false;
            //查找购物车中是否有该商品
            for(var i in productlist){
                if(productlist[i].id==product.id){
                    productlist[i].num=parseInt(productlist[i].num)+parseInt(product.num);
                    var _ratio = (productlist[i].num/productlist[i].totalNum)*100;
                    productlist[i].ratio = xround(_ratio,4);

                    result = true;
                }
            }
            if(!result){
                //没有该商品就直接加进去
            
            var _ratio = product.num/product.totalNum*100;
            
            var ratio = xround(_ratio,4)
                productlist.push({"id":product.id,"name":product.name,"num":product.num,"price":product.price,"ratio":ratio,"img":product.img,"totalNum":product.totalNum,"surplus":product.surplus});
            }
            //重新计算总价
            var totalNumber =productlist.length;
            jsonstr.totalNumber=parseInt(totalNumber);
            jsonstr.totalAmount=parseFloat(jsonstr.totalAmount)+(parseInt(product.num)*parseFloat(product.price));
            orderdetail.totalNumber = jsonstr.totalNumber;
           
            orderdetail.totalAmount = jsonstr.totalAmount;
            //保存购物车
            $api.setStorage("ShoppingCart","'"+JSON.stringify(jsonstr));
        }
    },
    //修改给买商品数量
    updateproductnum:function(id,num){
        var ShoppingCart = $api.getStorage("ShoppingCart");
        var jsonstr = JSON.parse(ShoppingCart.substr(1,ShoppingCart.length));
        var productlist = jsonstr.productlist;

        for(var i in productlist){
            if(productlist[i].id==id){
                jsonstr.totalNumber=parseInt(jsonstr.totalNumber)+(parseInt(num)-parseInt(productlist[i].num));
                jsonstr.totalAmount=parseFloat(jsonstr.totalAmount)+((parseInt(num)*parseFloat(productlist[i].price))-parseInt(productlist[i].num)*parseFloat(productlist[i].price));
                productlist[i].num=parseInt(num);
                var _ratio = (productlist[i].num/productlist[i].totalNum)*100;
                productlist[i].ratio = xround(_ratio,4);
                var totalNumber =productlist.length;
            jsonstr.totalNumber=parseInt(totalNumber);
                orderdetail.totalAmount = jsonstr.totalAmount;
                $api.setStorage("ShoppingCart","'"+JSON.stringify(jsonstr));
                return productlist[i].ratio;
            }
        }
    },
    //修改给买商品参与人次
    updateproduct:function(id,surplus){
       
        
       var ShoppingCart = $api.getStorage("ShoppingCart");
        var jsonstr = JSON.parse(ShoppingCart.substr(1,ShoppingCart.length));
        var productlist = jsonstr.productlist;

        for(var i in productlist){
            if(productlist[i].id==id){
                productlist[i].surplus=parseInt(surplus);
                
                
                $api.setStorage("ShoppingCart","'"+JSON.stringify(jsonstr));
                if(productlist[i].num>surplus){
                    cart.updateproductnum(id,surplus);

                }
                
                
            }
        }
        

                               
    },
    //获取购物车中的所有商品
    getproductlist:function(){
        var ShoppingCart = $api.getStorage("ShoppingCart");       

        var jsonstr = JSON.parse(ShoppingCart.substr(1,ShoppingCart.length));
      
        /*var productlist = new Array(); 
        productlist['list'] = jsonstr.productlist;*/
       var productlist = jsonstr['productlist'];
       var totalNumber =productlist.length;
            jsonstr.totalNumber=parseInt(totalNumber);
        orderdetail.totalAmount = jsonstr.totalAmount;
       /* productlist['totalNumber'] = orderdetail.totalNumber;
        productlist['totalAmount'] = orderdetail.totalAmount;*/

        return jsonstr;
    },
    //判断购物车中是否存在商品
    existproduct:function(id){
        var ShoppingCart = $api.getStorage("ShoppingCart");
        var jsonstr = JSON.parse(ShoppingCart.substr(1,ShoppingCart.length));
        var productlist = jsonstr.productlist;
        var result=false;
        for(var i in productlist){
            if(productlist[i].id==product.id){
                result = true;
            }
        }
        return result;
    },

    //删除购物车中商品
    deleteproduct:function(id){
        var ShoppingCart = $api.getStorage("ShoppingCart");
        var jsonstr = JSON.parse(ShoppingCart.substr(1,ShoppingCart.length));
        var productlist = jsonstr.productlist;
        var list=[];
        for(var i in productlist){
            if(productlist[i].id==id){
                var totalNumber =productlist.length;
                jsonstr.totalNumber=parseInt(totalNumber);
                jsonstr.totalAmount=parseFloat(jsonstr.totalAmount)-parseInt(productlist[i].num)*parseFloat(productlist[i].price);
            }else{
                list.push(productlist[i]);
            }
        }
        jsonstr.productlist = list;
        orderdetail.totalNumber = jsonstr.totalNumber;
        orderdetail.totalAmount = jsonstr.totalAmount;
        $api.setStorage("ShoppingCart","'"+JSON.stringify(jsonstr));
    }
};
//清单类结束

     /*$api.clearStorage();*/
//通过增减修改商品数量
function change(){
    var ul = $api.byId('cart');
    $api.addEvt(ul, 'change', function (e) {
        
        if(e.target.getAttribute("data-name") && e.target.tagName.toLowerCase()=='input'){
              
                var inputId = e.target.getAttribute("data-name");
                var inputTxt = $api.byId(inputId);
                var inputTxtval = $api.val(inputTxt);
                var num = parseInt($api.val(inputTxt));

                var surplus = $api.attr(inputTxt,'data-max');
                
                if(num>0&&num<=surplus){
                    $api.val(inputTxt,num);
                    var ratio =cart.updateproductnum(inputId,num);
                    /*var s =JSON.stringify($api.getStorage("ShoppingCart"));*/
                    var pId = inputId+'_ratio';
                    var pTxt = $api.byId(pId);
                    /*alert(pTxt);*/
                    $api.html(pTxt,'抽中几率：'+ratio+'%');
                    $api.html($api.byId('totalNumber'),orderdetail.totalNumber);
                    $api.html($api.byId('totalAmount'),orderdetail.totalAmount);

                    /*orderdetail.totalNumber;
                    orderdetail.totalAmount;*/
                }else{
                    if(num == 0){
                        num = 1;
                        $api.val(inputTxt,num);
                    var ratio =cart.updateproductnum(inputId,num);
                    /*var s =JSON.stringify($api.getStorage("ShoppingCart"));*/
                    var pId = inputId+'_ratio';
                    var pTxt = $api.byId(pId);
                    /*alert(pTxt);*/
                    $api.html(pTxt,'抽中几率：'+ratio+'%');
                    $api.html($api.byId('totalNumber'),orderdetail.totalNumber);
                    $api.html($api.byId('totalAmount'),orderdetail.totalAmount);

                    }
                    if(num>surplus){
                        num = surplus;
                        $api.val(inputTxt,num);
                    var ratio =cart.updateproductnum(inputId,num);
                    /*var s =JSON.stringify($api.getStorage("ShoppingCart"));*/
                    var pId = inputId+'_ratio';
                    var pTxt = $api.byId(pId);
                    /*alert(pTxt);*/
                    $api.html(pTxt,'抽中几率：'+ratio+'%');
                    $api.html($api.byId('totalNumber'),orderdetail.totalNumber);
                    $api.html($api.byId('totalAmount'),orderdetail.totalAmount);

                    }
                }
            }
    })
    $api.addEvt(ul, 'click', function (e) {
        
        /*alert(e.target.tagName);*/
            
            if(e.target.getAttribute("data-name") && e.target.getAttribute("data-pro")){
                var inputId = e.target.getAttribute("data-name");
                var inputTxt = $api.byId(inputId);
                var inputTxtval = $api.val(inputTxt);
                var num = parseInt(inputTxtval)+parseInt(e.target.getAttribute("data-pro"));
                var surplus = $api.attr(inputTxt,'data-max');
                
                if(num>0&&num<=surplus){
                    $api.val(inputTxt,num);
                    var ratio =cart.updateproductnum(inputId,num);
                    /*var s =JSON.stringify($api.getStorage("ShoppingCart"));*/
                    var pId = inputId+'_ratio';
                    var pTxt = $api.byId(pId);
                    /*alert(pTxt);*/
                    $api.html(pTxt,'抽中几率：'+ratio+'%');
                    $api.html($api.byId('totalNumber'),orderdetail.totalNumber);
                    $api.html($api.byId('totalAmount'),orderdetail.totalAmount);

                    /*orderdetail.totalNumber;
                    orderdetail.totalAmount;*/
                }
                
            }else if(e.target.getAttribute("data-name") && e.target.getAttribute("data")){
                var inputId = e.target.getAttribute("data-name");
                var inputTxt = $api.byId(inputId);
                var inputTxtval = $api.val(inputTxt);
                var num = parseInt(e.target.getAttribute("data"));
                var surplus = $api.attr(inputTxt,'data-max');
                
                if(num>0&&num<=surplus){
                    $api.val(inputTxt,num);
                    var ratio =cart.updateproductnum(inputId,num);
                    /*var s =JSON.stringify($api.getStorage("ShoppingCart"));*/
                    var pId = inputId+'_ratio';
                    var pTxt = $api.byId(pId);
                    /*alert(pTxt);*/
                    $api.html(pTxt,'抽中几率：'+ratio+'%');
                    $api.html($api.byId('totalNumber'),orderdetail.totalNumber);
                    $api.html($api.byId('totalAmount'),orderdetail.totalAmount);

                    /*orderdetail.totalNumber;
                    orderdetail.totalAmount;*/
                }
            }else if(e.target.getAttribute("data-name") && e.target.getAttribute("id")=='rand'){
                var inputId = e.target.getAttribute("data-name");
                var inputTxt = $api.byId(inputId);
                var inputTxtval = $api.val(inputTxt);
                var num = Math.round(Math.random()*100);
                var surplus = $api.attr(inputTxt,'data-max');
                
                if(num>0&&num<=surplus){
                    $api.val(inputTxt,num);
                    var ratio =cart.updateproductnum(inputId,num);
                    /*var s =JSON.stringify($api.getStorage("ShoppingCart"));*/
                    var pId = inputId+'_ratio';
                    var pTxt = $api.byId(pId);
                    /*alert(pTxt);*/
                    $api.html(pTxt,'抽中几率：'+ratio+'%');
                    $api.html($api.byId('totalNumber'),orderdetail.totalNumber);
                    $api.html($api.byId('totalAmount'),orderdetail.totalAmount);

                    /*orderdetail.totalNumber;
                    orderdetail.totalAmount;*/
                }
            }
            
        })
}



apiready = function(){
    getCart();
    change();
    api.setCustomRefreshHeaderInfo({
            bgColor : '#f0f0f0',
            image : {
                pull : 'widget://image/pull.png',
                transform : [
                    'widget://image/pull_end_image_frame_01.png',
                    'widget://image/pull_end_image_frame_02.png',
                    'widget://image/pull_end_image_frame_03.png',
                    'widget://image/pull_end_image_frame_04.png',
                    'widget://image/pull_end_image_frame_05.png'
                ],
                load : [
                    'widget://image/refreshing_image_frame_01.png',
                    'widget://image/refreshing_image_frame_02.png',
                    'widget://image/refreshing_image_frame_03.png',
                    'widget://image/refreshing_image_frame_04.png',
                    'widget://image/refreshing_image_frame_05.png',
                    'widget://image/refreshing_image_frame_06.png'
                ]
            }
        }, function() {
            //下拉刷新被触发，自动进入加载状态，使用 api.refreshHeaderLoadDone() 手动结束加载中状态
            setTimeout(function(){
                var refresh = true;
                getCart(refresh);
                
        api.refreshHeaderLoadDone();
            }, 800);
           
        });
    }


        /*清单列表部分
            
        */
       
        var getCart = function(refresh){

            var shopId= api.pageParam.shopId;


           /* if(shopId){
                //获取选中商品内容
               var aa = getCartData(shopId);           
               
            }else
*/

       
                 //是否存在清单内容
                var ShoppingCart = $api.getStorage("ShoppingCart");
                var jsonstr = JSON.parse(ShoppingCart.substr(1,ShoppingCart.length));
                var productlist = jsonstr.productlist;
                if(ShoppingCart){
                    
                     for(var i in productlist){
                        
                        api.ajax({
                        url: 'http://wap.jqmao.cn/getCartData',
                        method: 'post',
                        data: {
                            values: {shopId: productlist[i].id}
                        }
                    },function (ret, err) {
                        if(ret){
                           
                            var id = ret.id;
                            var surplus = ret.shenyurenshu;
                             cart.updateproduct(id,surplus);

                        var productlist=cart.getproductlist();//取出购物车商品

                               
                                var a =$api.byId('cart');
                                var tpl = $api.byId('cart-template').text;
                                var tempFn = doT.template(tpl);
                                $api.html(a,tempFn(productlist));
                                var a =$api.byId('cart');
                         }
                    })
                       
                     }
                    
             /*      
                if(shopId&!refresh){
                //获取选中商品内容
                    getCartData(shopId);           
               
                }
    */
                    
                } else{
                    var productlist = '';
                     var a =$api.byId('cart');
                    var tpl = $api.byId('cart-template').text;
                    var tempFn = doT.template(tpl);
                    $api.html(a,tempFn(productlist));
                    var w = api.frameWidth/2-70;
                    var h = api.frameHeight/2+30;
                    //alert(w)
                    var button = api.require('UIButton');
                    button.open({
                        rect:{
                           x: w,
                           y: h,
                           w: 140,
                           h: 36
                        },
                        corner: 5,
                        bg: {
                            normal: "#56ABE4",
                            highlight: '#98B7E5',
                            active: '#56ABE4'
                        },
                        title:{
                            size: 14,
                            highlight: '去逛逛',
                            active: '去逛逛',
                            normal: "去逛逛",
                            highlightColor: '#FFFFFF',
                            activeColor: '#FFFFFF',
                            normalColor: "#FFFFFF",
                            alignment: 'center'
                        },
                        fixedOn: api.frameName,
                        fixed: true,
                        move: true
        },function( ret ){        
            if( ret.eventType =='click' ){
                //alert( JSON.stringify( ret ) );
                openFrame(0)
            }
        });
                }
            }
            

        
        function getCartData(shopId){
      
           var product=null;
          
            api.ajax({
                url: 'http://wap.jqmao.cn/getCartData',
                method: 'post',
                data: {
                    values: {shopId: shopId}
                }
            },function (ret, err) {
                if(ret){
                    var id = ret.id;
                    var surplus = ret.shenyurenshu;
                    var name = ret.title;
                    var price = ret.yunjiage;
                    var img = ret.thumb;
                    var totalNum = ret.zongrenshu;
                    alert(JSON.stringify(ret))
                     product =
            {
                'id': id,        //属性名用引号括起来，属性间由逗号隔开
                'name': name,
                'num':10,
                'price':price,
                'img': img,
                'totalNum':totalNum,
                'surplus':surplus
            };
            
            
            //商品加入到购物车
            if(surplus!=0){
                cart.addproduct(product);
                var productlist=cart.getproductlist();//取出购物车商品
                //alert(JSON.stringify(productlist.productlist));
               
                var a =$api.byId('cart');
                    var tpl = $api.byId('cart-template').text;
                    var tempFn = doT.template(tpl);
                 
                    $api.html(a,tempFn(productlist));
                
            }
           
         
                }
            });

            /*alert(JSON.stringify(product))
            return product;*/
        }
      /*  function getcartData = */
      
        
   


